package com.daxidi.cn.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxidi.cn.annotation.LogAnnotation;
import com.daxidi.cn.entity.*;
import com.daxidi.cn.enums.LogTypeEnum;
import com.daxidi.cn.mapper.*;
import com.daxidi.cn.service.IShopService;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import com.daxidi.cn.utils.UuidUtils;
import com.daxidi.cn.vo.ShopBillVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商铺表 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Log4j
@Api(tags = "商家模块接口")
@RestController
@RequestMapping("/api/v1/union/shop")
public class ShopController {

    @Autowired
    private IShopService shopService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ClerkMapper clerkMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @LogAnnotation(content = "添加商家", type = LogTypeEnum.ADD)
    @ApiOperation(value = "商家模块  添加接口")
    @ApiResponses({
            @ApiResponse(code = 132, message = "添加成功"),
            @ApiResponse(code = 133, message = "添加失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/")
    public ReturnResult addShop(@RequestBody Shop shop) {
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", shop.getPhone());
        Shop shop1 = shopMapper.selectOne(wrapper);
        if (shop1 != null) {
            log.error("添加失败，手机号已存在");
            return ReturnResultUtils.returnFailMsg(133, "手机号已存在");
        }
        try {
            shop.setCreatedAt(new Date());
            shop.setUpdatedAt(null);
            shop.setDeletedAt(null);
            shopService.addShop(shop);
            //添加商店管理员
            Clerk clerk = new Clerk();
            clerk.setCreatedAt(new Date());
            clerk.setName(shop.getContact());
            //判断手机号是否存在
            QueryWrapper<Clerk> wrapper4 = new QueryWrapper<>();
            wrapper4.eq("moblie", shop.getPhone());
            if (clerkMapper.selectList(wrapper4).size() > 0) {
                return ReturnResultUtils.returnFailMsg(133, "手机号已经被注册！");
            }
            clerk.setMoblie(shop.getPhone());
            clerk.setRole(1);
            clerk.setEnable(true);
            String password = shop.getPhone().substring(shop.getPhone().length() - 6);
            clerk.setPassword(UuidUtils.sha1(password));
            QueryWrapper<Shop> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("phone", shop.getPhone());
            Shop shop2 = shopMapper.selectOne(wrapper2);
            clerk.setShopId(shop2.getId());
            clerkMapper.insert(clerk);
            //添加到user表
            QueryWrapper<Clerk> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("moblie", shop.getPhone());
            Clerk clerk1 = clerkMapper.selectOne(wrapper3);
            User user = new User();
            user.setClerkId(clerk1.getId());
            user.setCreatedAt(new Date());
            userMapper.insert(user);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("添加失败" + e);
            return ReturnResultUtils.returnFailMsg(133, "添加失败");
        }
    }

    @LogAnnotation(content = "删除商家", type = LogTypeEnum.DELETE)
    @ApiOperation(value = "商家模块  删除接口")
    @ApiResponses({
            @ApiResponse(code = 134, message = "删除成功"),
            @ApiResponse(code = 135, message = "删除失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @DeleteMapping("/{id}")
    public ReturnResult deleteShopById(@PathVariable("id") Long id) {
        QueryWrapper<Clerk> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", id);
        QueryWrapper<Bill> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("shop_id", id);
        QueryWrapper<Notice> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("type", id);
        if (clerkMapper.selectList(wrapper).size() > 0) {
            List<Clerk> clerkList = clerkMapper.selectList(wrapper);
            clerkList.forEach(clerk -> {
                clerkMapper.deleteById(clerk);
            });
        }
        if (billMapper.selectList(wrapper2).size() > 0) {
            List<Bill> billList = billMapper.selectList(wrapper2);
            billList.forEach(bill -> {
                billMapper.deleteById(bill);
            });
        }
        if (noticeMapper.selectList(wrapper3).size() > 0) {
            List<Notice> noticeList = noticeMapper.selectList(wrapper3);
            noticeList.forEach(notice -> {
                noticeMapper.deleteById(notice);
            });
        }
        try {
            shopService.deleteShopById(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("删除失败" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(135, "删除失败");
        }
    }

    @LogAnnotation(content = "修改商家信息", type = LogTypeEnum.UPDATE)
    @ApiOperation(value = "商家模块  修改接口")
    @ApiResponses({
            @ApiResponse(code = 136, message = "修改成功"),
            @ApiResponse(code = 137, message = "修改失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/updateShopById/{id}")
    public ReturnResult updateShopById(@RequestBody Shop shop) {
        try {
            Shop shop1 = shopService.selectShop(shop.getId());
            shop.setDeletedAt(null);
            shop.setUpdatedAt(new Date());
            shop.setCreatedAt(shop1.getCreatedAt());
            shopService.updateShopById(shop);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(137, "修改失败");
        }
    }

    @ApiOperation(value = "商家模块  查询接口", notes = "count:  为 数据的总条数")
    @ApiResponses({
            @ApiResponse(code = 138, message = "查询成功"),
            @ApiResponse(code = 139, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping
    public ReturnResult searchShop(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit, String boss, String phone, String beginTime, String endTime, String enable) {
        try {
            Map map = shopService.searchShop(page, limit, boss, phone, beginTime, endTime, enable);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(139, "查询失败");
        }
    }

    @ApiOperation(value = "根据Id查询商家")
    @GetMapping("/showOneShopById/{shopId}")
    public ReturnResult showOneShop(@PathVariable("shopId") Long shopId) {
        try {
            Shop shop = shopService.selectShop(shopId);
            return ReturnResultUtils.returnSuccess(shop);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(139, "查询失败");
        }
    }

    @ApiOperation(value = "商家模块  商店累计订单，累计金额接口", notes = "该接口是根据商店的id查询商店累计订单，累计金额接口，参数 shopId 为商店的id")
    @GetMapping("/selectShopById/{shopId}")
    public ReturnResult selectShopById(@PathVariable("shopId") Integer shopId) {
        ShopBillVo shopBillVo = shopService.selectShopBillVo(shopId);
        return ReturnResultUtils.returnSuccess(shopBillVo);
    }

    @ApiOperation(value = "商家模块  商家列表模糊查询", notes = "该接口是根据商店的名称查询商店信息,参数shopName是商店名称")
    @GetMapping("/selectLikeShops/{shopName}")
    public ReturnResult selectLikeShops(@PathVariable("shopName") String shopName) {
        List<ShopBillVo> shopBillVos = shopService.selectLikeShops(shopName);
        return ReturnResultUtils.returnSuccess(shopBillVos);
    }

    @ApiOperation(value = "商家模块  商家列表展示")
    @GetMapping("/selectShops")
    public ReturnResult selectShops() {
        List<ShopBillVo> shopBillVos = shopService.selectShops();
        return ReturnResultUtils.returnSuccess(shopBillVos);
    }

    @LogAnnotation(content = "导出商家信息", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "后台商家导出")
    @GetMapping("/downloadShop/")
    public ReturnResult downloadShop() {
        try {
            List<Shop> shops = shopMapper.selectList(null);
            return ReturnResultUtils.returnSuccess(shops);
        } catch (Exception e) {
            log.error("下载失败" + e);
            return ReturnResultUtils.returnFailMsg(198, "下载失败");
        }
    }

    @LogAnnotation(content = "恢复商家状态", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "恢复商家状态")
    @PutMapping("/updateEnable")
    public ReturnResult updateEnable(Integer id) {
        try {
            QueryWrapper<Shop> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Shop shop = shopMapper.selectOne(wrapper);
            shop.setEnable(1);
            shopMapper.updateById(shop);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("恢复失败" + e);
            return ReturnResultUtils.returnFailMsg(137, "恢复失败");
        }
    }

    @LogAnnotation(content = "下线商家", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "下线商家")
    @PutMapping("/windingEnable")
    public ReturnResult windingEnable(Integer id) {
        try {
            QueryWrapper<Shop> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Shop shop = shopMapper.selectOne(wrapper);
            shop.setEnable(0);
            shopMapper.updateById(shop);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("下线失败" + e);
            return ReturnResultUtils.returnFailMsg(137, "下线失败");
        }
    }
}
